package com.itheima.controller;

import com.itheima.domain.Fruit;
import com.itheima.domain.User;
import com.itheima.service.ManagerService;

import java.util.List;
import java.util.Scanner;
import java.util.TreeSet;

public class ManagerController {
    private Scanner sc = new Scanner(System.in);
    private ManagerService managerService = new ManagerService();


    public void start() {
        Scanner sc = new Scanner(System.in);
//管理员登录方法
        managerAdmain();
        ManagerLooper:
        while (true) {


            System.out.println("请输入您的选择: 1.管理用户  2.管理水果  3.退出 ");
            String choice = sc.next();
            switch (choice) {
                case "1":
                    //管理用户
                    manageUser();
                    break;
                case "2":
                    //管理水果
                    mangeFruit();
                    break;

                case "3":
                    break ManagerLooper;
                default:
                    System.out.println("输入有误，请重新输入");
            }

        }
    }

    private void mangeFruit() {
        //管理水果
        managerFruitLoop:
        while (true) {
            System.out.println("-----------水果管理系统------------");
            System.out.println("请输入您的选择： 1.上架水果  2.下架水果  3.修改水果  4.查看已上架水果  5.返回上一级");

            String choice = sc.next();

            switch (choice) {
                case "1":
                    addFruit();
                    break;

                case "2":
                    deleteFruit();
                    break;

                case "3":
                    updateFruit();
                    break;

                case "4":
                    checkFruit();
                    break;

                case "5":
                    break managerFruitLoop;

                default:
                    System.out.println("您的输入有误，请重新输入");
            }
        }
    }

    //判断水果数据是否为空
    private boolean isEmpty() {
        TreeSet<Fruit> fruitSet = managerService.getFruitSet();
        return fruitSet.size() == 0;
    }

    //判断水果id是否已存在，是则返回true，否则返回false
    public boolean isFruitIdExists(String id) {
        return managerService.isIdExists(id);
    }

    //判断水果名称是否已经存在,返回控制台输入的水果名称
    public String isFruitNameExists() {
        String updateName;
        while (true) {
            System.out.println("请输入水果名称:");
            updateName = sc.next();

            boolean nameExists = managerService.isNameExists(updateName);

            if (nameExists) {
                System.out.println("水果名称已存在，请重新输入");
            } else {
                return updateName;
            }
        }
    }

    //接着输入价格、库存，再封装为fruit方法
    public Fruit fruitPackage(String id, String name) {
        System.out.println("请输入价格：");
        double price = Double.parseDouble(sc.next());

        System.out.println("请输入库存数量：");
        int amount = sc.nextInt();

        return new Fruit(id, name, price, amount);
    }

    //上架水果方法
    public void addFruit() {
        //建立死循环，直到输入文件中尚未存在的水果id为止，或输入“#”返回
        String newId;
        while (true) {
            System.out.println("请输入水果id，以'f'开头，按#返回上一层:");
            newId = sc.next();
            if (newId.startsWith("f")) {
                boolean idExists = isFruitIdExists(newId);
                if (idExists) {
                    System.out.println("水果id已存在，请重新输入");
                } else {
                    break;
                }

            } else if ("#".equals(newId)) {
                return;
            } else {
                System.out.println("水果id必须以'f'开头，您的输入有误，请重新输入");
            }
        }

        //输入水果名称
        String newName = isFruitNameExists();

        Fruit newFruit = fruitPackage(newId, newName);
        managerService.addFruit(newFruit);
        System.out.println("上架成功！");
    }

    //下架水果方法
    public void deleteFruit() {
        boolean flag = isEmpty();

        if (flag) {
            System.out.println("暂无数据");
        } else {
            //建立死循环，直到输入文件中存在的水果id为止，或输入“#”返回
            deleteFruitLoop:
            while (true) {
                System.out.println("请输入你要下架的水果id,按#返回上一级:");
                String dleId = sc.next();
                if (!"#".equals(dleId)) {
                    boolean idExists = isFruitIdExists(dleId);
                    if (idExists) {
                        TreeSet<Fruit> allFruits = managerService.getFruitSet();

                        while (true) {
                            System.out.println("您确定要删除以下所示水果？(按y确认/按n否认)");
                            System.out.println("编号\t名称\t价格\t库存");

                            for (Fruit f : allFruits) {
                                if (dleId.equals(f.getId())) {
                                    System.out.println(f.getId() + "\t" + f.getName() + "\t" + f.getPrice() + "\t" + f.getAmount());
                                }
                            }

                            String s = sc.next();
                            switch (s) {
                                case "y":
                                    managerService.deleteFruit(dleId);
                                    System.out.println("删除成功");
                                    break deleteFruitLoop;

                                case "n":
                                    break deleteFruitLoop;

                                default:
                                    System.out.println("您的输入有误,请重新输入");
                            }
                        }
                    } else {
                        System.out.println("您的输入有误，请重新输入");
                    }
                } else {
                    return;
                }
            }
        }
    }

    //修改水果方法
    public void updateFruit() {
        boolean flag3 = isEmpty();
        if (flag3) {
            System.out.println("暂无数据");
        } else {
            updateFruitLoop:
            while (true) {
                System.out.println("请输入您要修改的水果的id,按#返回上一级:");
                String updateId = sc.next();

                if ("#".equals(updateId)) {
                    //输入#返回上一级
                    break;
                } else {
                    boolean idExists = isFruitIdExists(updateId);
                    if (idExists) {
                        TreeSet<Fruit> allFruits = managerService.getFruitSet();

                        while (true) {
                            System.out.println("编号\t名称\t价格\t库存");
                            for (Fruit f : allFruits) {
                                if (updateId.equals(f.getId())) {
                                    System.out.println(f.getId() + "\t" + f.getName() + "\t" + f.getPrice() + "\t" + f.getAmount());
                                }
                            }

                            System.out.println("您确定要修改此项信息？(y确认/n否认)");
                            String s = sc.next();

                            if ("y".equals(s)) {
                                String updateName = isFruitNameExists();

                                Fruit updateFruit = fruitPackage(updateId, updateName);
                                managerService.updateFruit(updateFruit);
                                System.out.println("修改成功！");

                                break updateFruitLoop;
                            } else if ("n".equals(s)) {
                                break updateFruitLoop;
                            } else {
                                System.out.println("您的输入有误，请重新输入");
                            }
                        }


                    } else {
                        System.out.println("您输入的水果id有误，请重新输入");
                    }
                }
            }
        }
    }

    //查看已上架水果方法
    public void checkFruit() {
        boolean flag4 = isEmpty();
        if (flag4) {
            System.out.println("暂无数据");
        } else {
            TreeSet<Fruit> allFruits = managerService.getFruitSet();
            System.out.println("编号\t  名称\t  价格\t   库存");
            for (Fruit f : allFruits) {
                System.out.println(f.getId() + "\t" + f.getName() + "\t" + f.getPrice() + "\t" + f.getAmount());
            }
        }
    }


    private void manageUser() {
        //管理用户
        Scanner sc = new Scanner(System.in);
        managerUserLoop:
        while (true) {
            System.out.println("请输入您的选择：1.注册新用户  2.编辑用户  3.查询用户 4.注销用户  5.退出");
            String choice = sc.next();
            switch (choice) {
                case "1":
                    //注册新用户
                    addUser();
                    break;
                case "2":
                    //编辑用户
                    updateUser();
                    break;
                case "3":
                    //查询用户
                    selectUser();
                    break;
                case "4":
                    deleteUser();
                    break;
                case "5":
                    break managerUserLoop;
                default:
                    System.out.println("输入有误，请重新输入");
                    break;
            }
        }
    }

    //注销用户
    private void deleteUser() {
        System.out.println("请输入要注销的用户账号：(输入n返回)");
        String id = sc.next();
        if(isPrevious(id)){
            return;
        }

        boolean result = isExists(id);

        if(!result){
            System.out.println("删除失败，该用户不存在");
            return;
        }

        managerService.deleteUser(id);
        System.out.println("删除成功");
    }

    private void selectUser() {
        previous:
        while(true){
            System.out.println("请输入您的选择：1.查询单个用户  2.查询所有用户  3.退出");
            String choice = sc.next();

            switch (choice){
                case "1":
                    selectById();
                    break;
                case "2":
                    selectAll();
                    break;
                case "3":
                    break previous;
                default:
                    System.out.println("输入有误，请重新输入");
            }
        }
    }

    private void selectAll() {
        List<User> list = managerService.selectAll();

        if(list.size() < 1){
            System.out.println("暂无用户信息");
            return;
        }

        System.out.println("用户名\t\t\t姓名\t\t余额\t\t积分 ");
        for (User u : list) {
            System.out.println(u.getId() + "\t\t   " + u.getName() + "\t\t" + u.getBalance() + "\t\t" + u.getPoints());
        }
    }

    private void selectById() {
        System.out.println("请输入查询的用户账号：(输入n返回)");
        String id = sc.next();
        if(isPrevious(id)){
            return;
        }

        boolean result = isExists(id);

        if(result){
            User u = managerService.selectById(id);
            System.out.println("用户名\t\t\t姓名\t\t余额\t\t积分 ");
            System.out.println(u.getId() + "\t\t   " + u.getName() + "\t\t" + u.getBalance() + "\t\t" + u.getPoints());
        }else {
            System.out.println("该用户不存在，请重新输入");
        }
    }

    //编辑用户
    private void updateUser() {
        String id;
        previous:
        while(true){
            System.out.println("请输入用户账号：(输入n返回)");
            id = sc.next();

            //判断接收数据是否为n，是就返回
            boolean flag = isPrevious(id);
            if(flag){
                return;
            }

            boolean result = isExists(id);

            if(!result){
                System.out.println("用户不存在，请重新输入");
            }else {
                break;
            }
        }

        //根据id获取用户对象
        User u = managerService.selectById(id);
        String name = u.getName();

        updateUserLoop:
        while (true) {
            System.out.println("用户姓名：" + name + " 请确认以下操作：1.改名  2.充值  3.退出");
            String choice = sc.next();
            switch (choice){
                case "1":
                    updateUserName(id);
                    break;
                case "2":
                    charGing(id);
                    break;
                case "3":
                    break updateUserLoop;
                default:
                    System.out.println("输入有误，请重新输入");
            }
        }
    }

    private boolean isPrevious(String id) {
        if(id.equals("n")){
            return true;
        }
        return false;
    }

    //充值业务（修改用户余额）
    private void charGing(String id) {
        System.out.println("请输入充值金额");
        String money = sc.next();
        if(isPrevious(money)){
            return;
        }

        managerService.charGing(id,Integer.parseInt(money));
        System.out.println("充值成功~");
    }

    private void updateUserName(String id) {
        System.out.println("请输入新的用户名：(输入n返回)");
        String name = sc.next();

        if(isPrevious(name)){
            return;
        }


        boolean result = managerService.updateUserName(id, name);
        if(result){
            System.out.println("修改成功");
        }else {
            System.out.println("修改失败");
        }
    }

    //注册新用户
    private void addUser() {
        String id;
        while (true) {
            System.out.println("请输入用户ID(输入n返回)：");
            id = sc.next();
            boolean previous = isPrevious(id);
            if(previous){
                return;
            }

            boolean flag = isExists(id);

            if (flag) {
                System.out.println("用户ID已被占用，请重新输入");
            } else {
                break;
            }
        }

        User user = inputUserInfo(id);

        if(user == null){
            return;
        }

        //将用户对象传递给业务层
        boolean result = managerService.addUser(user);

        if (result) {
            System.out.println("添加用户成功");
        } else {
            System.out.println("添加用户失败");
        }
    }

    private User inputUserInfo(String id) {
        System.out.println("请输入用户密码：(输入n返回)");
        String password = sc.next();
        if(isPrevious(password)){
            return null;
        }

        System.out.println("请输入用户姓名：(输入n返回)");
        String name = sc.next();
        if(isPrevious(name)){
            return null;
        }

        System.out.println("请输入用户充值金额：(输入n返回)");
        String money = sc.next();
        if(isPrevious(money)){
            return null;
        }

        System.out.println("请输入用户初始积分：(输入n返回)");
        String points = sc.next();
        if(isPrevious(points)){
            return null;
        }




        User user = new User(id, name, Double.valueOf(money), Integer.parseInt(points),password);

        return user;
    }

    private boolean isExists(String id) {
        return managerService.isExists(id);
    }

    private void managerAdmain() {
        while (true) {

            System.out.println("--------请登录管理账号--------");
            System.out.println("-------------------------------------");
            System.out.println("请输入您的账号");
            String id = sc.next();
            System.out.println("请输入您的密码");
            String password = sc.next();
            if (id.equals("root")&&password.equals("root")){

                System.out.println("登录成功，欢迎您");
                System.out.println("-------------------------------------");
                break;
            } else
                System.out.println("账号或密码错误，请检查后重试");
            System.out.println("-------------------------------------");


        }


    }
}
